<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="itemTypeName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="itemTypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--物料数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input
              v-model="queryParams.itemCode"
              placeholder="请输入物料编码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input
              v-model="queryParams.itemName"
              placeholder="请输入物料名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="Fefresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mes:md:mditem:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['mes:md:mditem:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['mes:md:mditem:remove']"
            >删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['mes:md:mditem:import']"
            >导入</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['mes:md:mditem:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="物料编码" width = "120" align="center" key="itemCode" prop="itemCode" v-if="columns[0].visible" >
              <template #default="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleView(scope.row)"
                  v-hasPermi="['mes:md:mditem:query']"
                >{{scope.row.itemCode}}</el-button>
              </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="120" align="left" key="itemName" prop="itemName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="规格型号" align="left" key="specification" prop="specification" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="单位" align="center" key="unitOfMeasure" prop="unitOfMeasure" v-if="columns[3].visible" :show-overflow-tooltip="true" >
          </el-table-column>
          <el-table-column label="物料/产品" align="center" key="itemOrProduct" prop="itemOrProduct" v-if="columns[4].visible" :show-overflow-tooltip="true" >
            <template #default="scope">
              <dict-tag :options="mes_item_product" :value="scope.row.itemOrProduct"/>
            </template>
          </el-table-column>

          <el-table-column label="所属分类" align="center" key="itemTypeName" prop="itemTypeName" v-if="columns[5].visible" width="120" />
          <el-table-column label="是否启用" align="center" key="enableFlag" v-if="columns[6].visible">
            <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.enableFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="设置安全库存" align="center" key="safeStockFlag" v-if="columns[7].visible">
            <template #default="scope">
              <dict-tag :options="sys_yes_no" :value="scope.row.safeStockFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[8].visible" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:md:mditem:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mes:md:mditem:remove']"
              >删除</el-button>              
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改物料产品编码对话框 -->
    <el-dialog :title="title" v-model="open" width="960px" append-to-body>
      <el-form ref="itemForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="itemCode">
              <el-input v-model="form.itemCode" readonly="readonly" maxlength="64" v-if="optType == 'view'"/>
              <el-input v-model="form.itemCode" placeholder="请输入物料编码" maxlength="64" v-else/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item  label-width="80" >

                <el-switch v-model="autoGenFlag"
                    active-color="#13ce66"
                    active-text="自动生成"
                    @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view'">               
                </el-switch>
  
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName"  maxlength="255" readonly="readonly" v-if="optType=='view'" />
              <el-input v-model="form.itemName" placeholder="请输入物料名称" maxlength="255" v-else/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" type="textarea" maxlength="500" readonly="readonly" v-if="optType=='view'" />
              <el-input v-model="form.specification" type="textarea" placeholder="请输入规格型号" maxlength="500" v-else/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">    
               <el-select v-model="form.unitOfMeasure" disabled v-if="optType=='view'">
                <el-option
                    v-for="item in measureOptions"
                    :key="item.measureCode"
                    :label="item.measureName"
                    :value="item.measureCode"
                    :disabled="item.enableFlag == 'N'"
                  ></el-option>
              </el-select>

              <el-select v-model="form.unitOfMeasure" placeholder="请选择单位" v-else>
                <el-option
                    v-for="item in measureOptions"
                    :key="item.measureCode"
                    :label="item.measureName"
                    :value="item.measureCode"
                    :disabled="item.enableFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="物料/产品分类" prop="itemTypeId">
              <el-tree-select v-model="form.itemTypeId" 
              :data="itemTypeOptions" 
              :props="{ value: 'id', label: 'label', children: 'children' }"
              :show-count="true" disabled v-if="optType=='view'"  />

              <el-tree-select v-model="form.itemTypeId" 
              :data="itemTypeOptions" 
              :props="{ value: 'id', label: 'label', children: 'children' }"
              :show-count="true" 
              placeholder="请选择所属分类" v-else :disable-branch-nodes="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用">
                <el-radio-group v-model="form.enableFlag" disabled v-if="optType=='view'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
              <el-radio-group v-model="form.enableFlag" v-else>
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全库存">
              <el-radio-group v-model="form.safeStockFlag" disabled v-if="optType=='view'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>

              <el-radio-group v-model="form.safeStockFlag" v-else>
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.safeStockFlag == 'Y'">
          <el-col :span="12">
            <el-form-item label="最小库存量">
              <el-input-number v-model="form.minStock" :percision="2" :step="1" disabled v-if="optType=='view'" />
              <el-input-number v-model="form.minStock" :percision="2" :step="1" placeholder="请输入最小安全库存量" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大库存量">
              <el-input-number v-model="form.maxStock" :percision="2" :step="1" disabled v-if="optType=='view'" />
              <el-input-number v-model="form.maxStock" :percision="2" :step="1" placeholder="请输入最大安全库存量" v-else/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" readonly v-if="optType=='view'"></el-input>
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" v-else></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <el-tabs type="border-card" v-if="form.itemId != null">        
        <el-tab-pane label="BOM组成">
          <ItemBom :optType="optType" :itemId="form.itemId"></ItemBom>          
        </el-tab-pane>
        <el-tab-pane label="供应商"></el-tab-pane>
        <el-tab-pane label="替代品"></el-tab-pane>
        <el-tab-pane label="SIP"></el-tab-pane>
        <el-tab-pane label="SOP">
          <SOPTab :itemId="form.itemId" :optType="optType"></SOPTab>
        </el-tab-pane>
      </el-tabs> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel" v-if="optType =='view'">返回</el-button>
          <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
    </template>
    </el-dialog>

    <!-- 物料导入对话框 -->
    <!-- <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script setup class="MdItem">
import { listMdItem, getMdItem, delMdItem, addMdItem, updateMdItem} from "@/api/mes/md/mdItem";

// import ItemBom from "./components/itembom.vue";
// import SOPTab from  "./components/sop.vue"
import { listAllUnitmeasure} from "@/api/mes/md/unitmeasure";
import {genCode} from "@/api/system/autocode/rule"
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/mes/md/itemtype";
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";

const { proxy } = getCurrentInstance();
const { sys_yes_no, mes_item_product } = proxy.useDict("sys_yes_no","mes_item_product");

const loading = ref(true);// 遮罩层
const ids = ref([]); // 选中数组
const showSearch = ref(true);// 显示搜索条件
const single = ref(true);// 非单个禁用
const multiple = ref(true);// 非多个禁用
const total = ref(0);// 总条数
const title = ref(""); // 弹出层标题
const open = ref(false);// 是否显示弹出层
const itemList = ref(null); // 物料产品表格数据
const itemTypeOptions = ref([]); //部门树选项

const dateRange = ref([]);// 日期范围
const measureOptions = ref([]);// 单位列表

const optType = ref(undefined);//弹框的操作类型 view add edit
const itemTypeName = ref(undefined);// 部门名称
const autoGenFlag = ref(false);// 自动生成物料编码标识

const columns = ref([
        { key: 0, label: `物料/产品编码`, visible: true },
        { key: 1, label: `物料/产品名称`, visible: true },
        { key: 2, label: `规格型号`, visible: true },
        { key: 3, label: `单位`, visible: true },
        { key: 4, label: `物料/产品`, visible: true },
        { key: 5, label: `物料分类`, visible: true },
        { key: 6, label: `是否启用`, visible: true },
        { key: 7, label: `是否设置安全库存`, visible: true },
        { key: 8, label: `创建时间`, visible: true }
      ]);// 列信息

const data = reactive({
  form: {},// 表单参数

  defaultProps: {
        children: "children",
        label: "label"
  },
  // 用户导入参数
  upload: {
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/mes/md/mditem/importData"
  },


  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemCode: undefined,
    itemName: undefined,
    itemTypeId: 0
  },
  // 表单校验
  rules: {
    itemCode: [
      { required: true, message: "物料/产品编码不能为空", trigger: "blur" },
      { max: 64, message: '物料/产品编码长度必须小于64个字符', trigger: 'blur' }
    ],
    itemName: [
      { required: true, message: "物料/产品名称不能为空", trigger: "blur" }
    ],
    unitOfMeasure: [
      { required: true, message: "单位不能为空",trigger: "blur"}
    ],
    itemTypeId: [
      { required: true, message: "物料分类不能为空", trigger: "blur" },
    ]
  }
});

const { queryParams, form, rules, defaultProps, upload } = toRefs(data);//对象解构

/** 查询物料编码列表 */
function getList() {
      loading.value = true;
      listMdItem(queryParams.value).then(response => {
          itemList.value = response.rows;
          total.value = response.total;
          loading.value = false;
        }
      );
}
function getUnits(){
  listAllUnitmeasure().then(response =>{
    measureOptions.value = response.data;
  });
}
/** 查询分类下拉树结构 */
function getTreeselect() {
  treeselect().then(response => {
    itemTypeOptions.value = response.data;
  });
}
// 筛选节点
function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

// 节点单击事件
function handleNodeClick(data) {
  queryParams.value.itemTypeId = data.id;
  handleQuery();
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    itemId: undefined,
    itemTypeId: undefined,
    itemCode: undefined,
    itemName: undefined,
    specification: undefined,
    unitOfMeasrue: undefined,
    enableFlag: undefined,
    itemOrProduct: undefined,
    enableFlag: 'Y',
    safeStockFlag: 'N',
    minStock: 0,
    maxStock: 0,
    optType: undefined,
    remark: undefined        
  };
  autoGenFlag.value = false;
  proxy.resetForm("itemForm");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itemId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 查询明细按钮操作
function handleView(row){
  reset();
  getTreeselect();
  const itemId = row.itemId || ids.value;
  getMdItem(itemId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看物料/产品";
    optType.value = "view";
  });
}
    
/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTreeselect();
  if(queryParams.value.itemTypeId != 0){
    form.value.itemTypeId = queryParams.value.itemTypeId;
  }
  optType.value = "add";
  open.value = true;
  title.value = "新增物料/产品";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTreeselect();
  const itemId = row.itemId || ids.value;
  getMdItem(itemId).then(response => {
    form.value = response.data;
    open.value = true;
    optType.value = "edit";
    title.value = "修改物料/产品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["itemForm"].validate(valid => {
    if (valid) {
      if (form.value.itemId != undefined) {
        updateMdItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMdItem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const itemIds = row.itemId || ids.value;
  proxy.$modal.confirm('确认删除数据项？').then(function() {
    return delMdItem(itemIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mes/md/mditem/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}
/** 导入按钮操作 */
function handleImport() {
  upload.value.title = "物料/产品导入";
  upload.value.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download('mes/md/mditem/importTemplate', {
  }, `md_item_${new Date().getTime()}.xlsx`)
}
// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}

// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.value.open = false;
  upload.value.isUploading = false;
  proxy.$refs.upload.clearFiles();
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}
// 提交上传文件
function submitFileForm() {
  proxy.$refs.upload.submit();
}
//自动生成物料编码
function handleAutoGenChange(autoGenFlag){

  if(autoGenFlag){
    genCode('ITEM_CODE').then(response =>{
      form.value.itemCode = response;
    });
  }else{
    form.value.itemCode = null;
  }
}

 // 监听 itemTypeName 变化，根据名称筛选分类树
watch(itemTypeName, (val) => {
  proxy.$refs.tree.filter(val);
});

getList();
getTreeselect();
getUnits();


</script>
